
#include <logger.hpp>

#include "table_schema_manager.hpp"

namespace xbase
{
	bool table_schema_manager::update_or_add(table_schema::pointer p_schema)
	{
		bool _ret = false;
		Guard<ReadWriteLock::WriteLock> _guard(m_schemas_lock.write_lock());
		schema_map::iterator iter = m_schemas.find(p_schema->table_name());
		if (iter == m_schemas.end())
		{
			std::pair<schema_map::iterator, bool>
				__ret = m_schemas.insert(schema_map::value_type(p_schema->table_name(),
									       p_schema));
			if (__ret.second) {
				LOG(INFO, "table_schema_manager::update_or_add"
				    << " table schema of '" << p_schema->table_name() << "' added.");
				_ret = true;
			} else {
				LOG(INFO, "table_schema_manager::update_or_add"
				    << " table schema of '" << p_schema->table_name() << "' failed to add.");
				_ret = false;
			}
		}
		else
		{
			// replace previous one
			iter->second.swap(p_schema); // TODO: the old ptr's weak_ptr would be expired?
			LOG(INFO, "table schema of '" << p_schema->table_name() << "' updated.");
			_ret = true;
		}
		return _ret;
	}

	table_schema::pointer table_schema_manager::get_schema(const std::string &p_table_name)
	{
		Guard<ReadWriteLock::ReadLock> _guard(m_schemas_lock.read_lock());
		schema_map::iterator iter = m_schemas.find(p_table_name);
		table_schema::pointer _schema; // default value
		if (iter != m_schemas.end())
		{
			_schema = iter->second;
		}
		else
		{
			LOG(WARN, "table_schema_manager::get_schema "
			    << p_table_name << "'s schema not exists.");
		}
		return _schema;
	}

} // namespace xbase
